@page "/Star"
@using System.Security.Claims
@inject SwalService SwalService
@inject NavigationManager NavigationManager
@using BootstrapBlazorApp.Server.Components.CustomComponent;

<PageTitle>个人中心</PageTitle>

<Layout ShowGotoTop="true" ShowCollapseBar="false"  SideWidth="100"
        IsPage="true">
    <Header>
        <HeaderComponent User="@user" OnQuestionsFiltered="HandleQuestionsFiltered" Questions="questions" Type="false"></HeaderComponent>
    </Header>
    <Side>
        <div style="justify-content: center; ">
            <div style="text-align: center;margin-top: 270px;margin-left: 30px;writing-mode: vertical-lr;">
                <text class="logo-title" style="color: #6a6a6a;font-size: x-large">我的收藏</text>
                <i class="bi bi-star-fill" style="color: #fae558;font-size: x-large" ></i>
            </div>
            
        </div>
    </Side>
    <Main>
        <div style="width: 80%;margin:0 auto;align-items: center">
            <Table TItem="QuestionWithStatus"  IsStriped="true" AllowResizing="true" IsPagination="true" PageItemsSource="@PageItemsSource" OnQueryAsync="OnQueryAsync">
                <TableColumns>
                    @*收藏状态*@
                    <TableColumn @bind-Field="@context.QId" Width="110" Align="Alignment.Center" Text="收藏状态">
                        <Template Context="value">
                            <i class="bi bi-star-fill" style="color: #f6d70e"  @onclick="() => removeStar(value.Value)"></i>
                        </Template>
                    </TableColumn>
                    @*完成状态*@
                    <TableColumn @bind-Field="@context.Status" Width="105" Align="Alignment.Center">
                        <Template Context="value">
                            @if (value.Value)
                            {
                                <i class="bi bi-check-circle" style="color: #28a745;"></i>
                            }
                            else
                            {
                                <i class="bi bi-dash"></i>
                            }
                        </Template>
                    </TableColumn>

                    @*题目名*@
                    <TableColumn @bind-Field="@context.Title" Width="500" Align="Alignment.Center">
                        <Template Context="value">
                            <a href="/qdetail/@value.Row.QId">@value.Value</a>
                        </Template>
                    </TableColumn>

                    @*题目标签*@
                    <TableColumn @bind-Field="@context.Tag" Align="Alignment.Center">
                        <Template Context="value">
                            @*假设全部tag作为一个字符串存储，用、分隔*@
                            @foreach (var tag in value.Value.Split('、'))
                            {
                                <div class="col-4 col-sm-auto" style="margin-right: 5px">
                                    <Tag Color="Color.Warning">@tag</Tag>
                                </div>
                            }
                        </Template>
                    </TableColumn>

                    @*难度*@
                    <TableColumn @bind-Field="@context.Difficulty" Width="100" Align="Alignment.Center" Filterable="true">
                        <FilterTemplate>
                            <MultiFilter ShowSearch="false" Items="questionWithStatus.Select(i => new SelectedItem(i.Difficulty.ToString()!, i.Difficulty.ToString()!)).DistinctBy(i => i.Value)"></MultiFilter>
                        </FilterTemplate>
                        <Template Context="value">
                            <div class="@setDifficultyColor(@value.Value)">@value.Value</div>
                        </Template>
                    </TableColumn>
                </TableColumns>
            </Table>
        </div>

    </Main>
</Layout>

@inject AuthenticationStateProvider AuthenticationStateProvider
@code {
    private ClaimsPrincipal? _user;
    private string PlaceHolderText = "请输入用户名";
    private User user;
    private User newUser=new User();
    
    private List<StarList> stars= new List<StarList>();
    private List<QuestionWithStatus> questionWithStatus = new List<QuestionWithStatus>();
    public List<Question> questions = new List<Question>();
    
    private static IEnumerable<int> PageItemsSource => new int[]
    {
        10,
        20,
        50
    };
    private Task<QueryData<QuestionWithStatus>> OnQueryAsync(QueryPageOptions options)
    {
        // 通过 options 获得用户组合的过滤条件
        var filters = options.ToFilter();

        // 使用内置扩展方法 ToFilter 获得过滤条件
        var items = questionWithStatus.Where(filters.GetFilterFunc<QuestionWithStatus>());
        //获得总数
        var enumerable = items.ToList();
        var total = enumerable.Count;
        // 内存分页
        items = enumerable.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();
    
        return Task.FromResult(new QueryData<QuestionWithStatus>()
        {
            Items = items,
            TotalCount = total,
            IsFiltered = filters.HasFilters()
        });
        
    }
    protected override async Task OnInitializedAsync()
    {
        base.OnInitialized();
        //获取当前用户对象
        _user = (await AuthenticationStateProvider.GetAuthenticationStateAsync()).User;
        
        if (_user == null)
        {
            return;
        }

        var value = _user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        if (value != null)
        {
            var user_id = int.Parse(value);
            user = User.Find(user_id);
        }

        if (user == null)
        {
            await SwalService.Show(new SwalOption()
            {
                Category = SwalCategory.Error,
                Content = "用户获取失败",
                Title = "系统错误"
            });
            return;
        }
        
        GetAllStar();
    }
    
    private Task OnSearch(string searchText)
    {
        questionWithStatus.Clear();
        //获取题目
        getALLStatus();
        questionWithStatus = questionWithStatus.Where(q => q.Title.Contains(searchText)).ToList();
        StateHasChanged();
        return Task.CompletedTask;
    }
    
    
    private async Task HandleQuestionsFiltered(List<QuestionWithStatus> qs)
    {
        questionWithStatus = qs;
        StateHasChanged();
    }
    private void GetAllStar()
    {
        stars=StarList.Where(s=>s.UserID==user.Id).ToList();
        getALLStatus();
    }
    private void getALLStatus()
    {
        //获取题目列表
        var questionIds = stars.Select(ad => ad.QuestionID).Distinct();
        questions = Question
            .Where(q => questionIds.Contains(q.Id))
            .ToList();
        
        foreach (var q in questions)
        {
            bool st = false;
            var record=AnswerDetail.Where(a => a.QuestionId == q.Id && a.UserId == user.Id).First();
            if (record != null)
            {
                st = true;
            }
            questionWithStatus.Add(new QuestionWithStatus(){
                QId =q.Id, 
                Title=q.Title,
                Tag=q.Tag,
                Difficulty=q.Difficulty,
                Category=q.Category,
                Status=st
            });
        }
    }
    private void gotoPersonPage()
    {
        NavigationManager.NavigateTo("/PersonalPage");
    }
    private string setDifficultyColor(string dif)
    {
        switch (dif)
        {
            case "简单": 
                return "easy-color";
                break;
            case "中等":
                return "medium-color";
                break;
            case "困难":
                return "hard-color";
                break;
            default:
                return "";
        }
    }
    private void removeStar(int Qid)
    {
        var s=StarList.Where(ss=>ss.QuestionID==Convert.ToInt32(Qid)&&ss.UserID==user.Id).First();
        if (s != null)
        {
            s.Delete();
        }
        questionWithStatus.Clear();
        //获取题目
        GetAllStar();
        getALLStatus();
        StateHasChanged();
        OnInitializedAsync();
    }
}



